How I´m becoming a coding guy

Welcome to this journey, everybody is invited to explore and collaborate!

A Python Script to run PowerShell commands!

I faced the need to create a Python script to extract several information from a windows server using PowerShell commands.June 9, 2020

Hi there!

We have a task called hardening, to start working on it we need to extract information from several servers, this is another time consuming task so we decided to automate it with Python!

The script will extract the information, save it to a file, then will create a new file with the previous file information to guarantee that results were not manipulated.

Again, this won´t be a tutorial so you will need to revise the code and if you need any detail just ping me.

Let's start!

This will show us what is the current working directory, just for check.

                        
                            # GET WORKING DIRECTORY
                            current_dir = os.getcwd()
                            print(current_dir)           
                        
                    

I created this validation step to check if the file that the script will create after run already exist. This will give you the change to back up the existing file before re-write in it:

                        
                            # VALIDATION FOR EVIDENCIAS.TXT - IF EXIST
                            flag = 'no_salir'
                            
                            while flag == 'no_salir':
                                if (os.path.isfile("evidencias.txt")) == True:
                                    rta= input('Existe un archivo con el mismo nombre que el que se va a genererar (evidencias.txt), 
                                    si desea eliminarlo ingrese y: ')
                                    if rta == 'y':
                                        os.remove("evidencias.txt")
                                        flag == 'salir'
                                        break
                                
                                    else:
                                        flag == 'no_salir'
                                        
                                else:
                                    flag == 'salir'
                                    break
                            # END VALIDATION FOR EVIDENCIAS.TXT - IF EXIST                                     
                        
                    

The code will create a txt file, with a header information:

                        
                            file = open('evidencias.txt','w')

                            with file:
                                
                                file.write("##COMIENZO SCRIPT##\n\n")
                                file.write("##Información de ejecución##\n\n")
                                file.write('###################################################\n')  

                                # SET DATE | HOSTNAME | DIR   
                                fecha = datetime.datetime.now()
                                file.write('Fecha y hora de inicio: ')
                                file.write(str(fecha)+'\n\n')
                                
                                com_a = subprocess.run('hostname', shell=True, capture_output = True)
                                file.write('Hostname: ')
                                
                                file.write(com_a.stdout.decode())
                                
                            
                                com_b = subprocess.run('dir', shell=True, capture_output = True)
                                file.write('Directorio de ejecución:\n\n ')
                                
                                file.write(com_b.stdout.decode())                                 
                        
                    

Then the PowerShell commands will extract the information and save this into the file. I will share just two of them but you can run any command.

                        
                            # START P.S. COMMANDS FOR HARDENING
                            file.write("##Ejecución de comandos##\n\n")
                            file.write('###################################################\n') 
                        
                            com_1 = subprocess.run('net share', shell=True, capture_output = True)
                            file.write('PUNTO DE CONTROL: Unidades compartidas (Share) no deben asignar permisos al grupo Everyone.\n')
                            file.write('COMANDO: Net Share.\n ')
                            
                            file.write(com_1.stdout.decode())
                            if com_1.stderr.decode() == '':
                                file.write('Comando finalizado.\n')
                                file.write('###################################################\n')
                            else:    
                                file.write('Se encontraron errores:' + " " + '---->' + " " + com_1.stderr.decode())
                                file.write('###################################################\n')
                                
                              
                            com_2 = subprocess.run(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", 'icacls', 'c:'], 
                            shell=True, capture_output = True)
                            file.write('PUNTO DE CONTROL: Asignar en forma recursiva los siguientes permisos a cada disco del sistema 
                            a partir del directorio raíz.\n')
                            file.write('COMANDO: icacls c.\n\n')
                            
                            file.write(com_2.stdout.decode())
                            if com_2.stderr.decode() == '':
                                file.write('Comando finalizado.\n')
                                file.write('###################################################\n')
                            else:    
                                file.write('Se encontraron errores:' + " " + '---->' + " " + com_2.stderr.decode())
                                file.write('###################################################\n')
                                
                                                    
                        
                    

And to guarantee that results are not manipulated I created a new file with the evidencias.txt hash information:

                        
                            # GET THE HASH AND CREATE A FILE WITH THIS INFORMATION

                            file = open('hash-info.txt','w')
                            
                            with file:
                            
                                com_hash = subprocess.run(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", 
                                'Get-FileHash evidencias.txt | Format-List'], shell=True, capture_output = True)
                                file.write('Comando: hash: \n ')
                                
                                file.write(com_hash.stdout.decode())
                                if com_hash.stderr.decode() == '':
                                    file.write('Comando finalizado.\n')
                                    file.write('###################################################\n')
                                else:    
                                    file.write('Se encontraron errores:' + " " + '---->' + " " + com_hash.stderr.decode())
                                    file.write('###################################################\n')